package mergeSort;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
        int [] a = {45,67,34,23,12,67,90};
        mergeSort(a);
        System.out.println(Arrays.toString(a));
    }
    //时间复杂度:O(nlogn)
    //空间复杂度:O(n)
    //稳定性:稳定
    private static void mergeSort(int[] a) {
        mergeSortChild(a,0,a.length-1);
    }

    private static void mergeSortChild(int[] a, int left, int right) {
        if(left >= right){
            return;
        }
        int mid = (left + right)/2;
        mergeSortChild(a,left,mid);
        mergeSortChild(a,mid+1,right);
        merge(a,left,mid,right);
    }

    private static void merge(int[] a, int left,int mid  ,int right) {
        int[] tmp = new int[right-left+1];
        int k = 0;
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        while (s1 <= e1 && s2 <= e2){
            if(a[s1] < a[s2]){
                tmp[k++] = a[s1++];
            }else {
                tmp[k++] = a[s2++];
            }
        }
        while (s1 <= e1){
            tmp[k++] = a[s1++];
        }
        while (s2 <= e2){
            tmp[k++] = a[s2++];
        }
        for (int i = 0; i < k; i++) {
            a[i+left] = tmp[i];

        }

    }
}
